package com.baiyinet.util;


import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.baiyinet.BuildConfig;
import com.baiyinet.R;
import com.baiyinet.biz.WechatShareManager;
import com.baiyinet.rest.CustomTrust;
import com.baiyinet.rest.UnSafeHostnameVerifier;
import com.baiyinet.ui.general.GeneralActivity_;
import com.baiyinet.ui.main.MainActivity_;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.sina.weibo.SinaWeibo;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ShareUtils {

    /**
     * 显示分享面板
     *
     * @param activity 上下文
     * @param title    标题
     * @param content  内容
     * @param shareUrl 分享地址
     * @param iconUrl  分享icon
     */
    public static void showSharePanel(final Activity activity, final String title, final String content,
                                      final String shareUrl, final String iconUrl, final String timelineMode, final String timelineFun) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (activity == null) {
                    return;
                }

                final boolean isImgUrlWork = checkURL(activity, iconUrl);

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        OnekeyShare oks = new OnekeyShare();
                        // 关闭sso授权
                        oks.disableSSOWhenAuthorize();

                        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
                        oks.setTitle(title);
                        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
                        oks.setTitleUrl(shareUrl);
                        // text是分享文本，所有平台都需要这个字段
                        oks.setText(content);
                        if (isImgUrlWork) {
                            // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
                            oks.setImageUrl(iconUrl);
                        }
                        // url仅在微信（包括好友和朋友圈）中使用
                        oks.setUrl(shareUrl);
                        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
                        oks.setComment(content);
                        // site是分享此内容的网站名称，仅在QQ空间使用
                        oks.setSite(activity.getString(R.string.app_name));
                        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
                        oks.setSiteUrl(shareUrl);
                        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
                            @Override
                            public void onShare(Platform platform, Platform.ShareParams paramsToShare) {
                                if (SinaWeibo.NAME.equals(platform.getName())) {
                                    String text = content.concat(shareUrl);
                                    paramsToShare.setText(text);
                                }
                            }
                        });
                        // 添加回调事件
                        oks.setCallback(new PlatformActionListener() {
                            @Override
                            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(activity, "分享成功", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                            @Override
                            public void onError(Platform platform, int i, Throwable throwable) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(activity, "分享失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                            @Override
                            public void onCancel(Platform platform, int i) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(activity, "取消分享", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        });

                        // 自定义朋友圈分享
                        Bitmap logo = BitmapFactory.decodeResource(activity.getResources(), R.drawable.ssdk_oks_classic_wechatmoments);
                        String label = "微信朋友圈";
                        oks.setCustomerLogo(logo, label, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if ("link".equalsIgnoreCase(timelineMode)) {
                                    // 直接分享链接
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            WechatShareManager wechatShareManager = new WechatShareManager(activity);
                                            WechatShareManager.ShareContentWebPage shareContentWebPage = (WechatShareManager.ShareContentWebPage) wechatShareManager.getShareContentWebPage(title, title, shareUrl, iconUrl);
                                            wechatShareManager.shareByWebchat(shareContentWebPage, WechatShareManager.WECHAT_SHARE_TYPE_TIMELINE);
                                        }
                                    }).start();
//                                    shareUrlToWeChatMoment(activity, title, shareUrl, iconUrl);
                                } else if (!TextUtils.isEmpty(timelineFun)) {
                                    // 九宫图分享
                                    if (activity instanceof GeneralActivity_) {
                                        ((GeneralActivity_) activity).loadUrl("javascript:" + timelineFun + "();");
                                    } else if (activity instanceof MainActivity_) {
                                        ((MainActivity_) activity).loadUrl("javascript:" + timelineFun + "();");
                                    }
                                }
                            }
                        });
                        // 启动分享GUI
                        oks.show(activity);

                        ClipboardManager clip = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
                        clip.setPrimaryClip(ClipData.newPlainText(null, content));
                        Utils.UI.showToastLong("内容已复制到剪贴板,长按粘贴");

                    }
                });
            }
        }).start();
    }

    public static void showSharePanel(final Activity activity, final String title, final String content,
                                      final String shareUrl, final String iconUrl) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (activity == null) {
                    return;
                }

//                final boolean isImgUrlWork = checkURL(activity, iconUrl);

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        OnekeyShare oks = new OnekeyShare();
                        // 关闭sso授权
                        oks.disableSSOWhenAuthorize();

                        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
                        oks.setTitle(title);
                        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
                        oks.setTitleUrl(shareUrl);
                        // text是分享文本，所有平台都需要这个字段
                        oks.setText(content);
//                        if (isImgUrlWork) {
//                            // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//                            oks.setImagçeUrl(iconUrl);
//                        }

                        oks.setImageUrl(iconUrl);

                        // url仅在微信（包括好友和朋友圈）中使用
                        oks.setUrl(shareUrl);
                        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
                        oks.setComment(content);
                        // site是分享此内容的网站名称，仅在QQ空间使用
                        oks.setSite(activity.getString(R.string.app_name));
                        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
                        oks.setSiteUrl(shareUrl);
                        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
                            @Override
                            public void onShare(Platform platform, Platform.ShareParams paramsToShare) {
                                if (SinaWeibo.NAME.equals(platform.getName())) {
                                    String text = content.concat(shareUrl);
                                    paramsToShare.setText(text);
                                }
                            }
                        });
                        // 添加回调事件
                        oks.setCallback(new PlatformActionListener() {
                            @Override
                            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(activity, "分享成功", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                            @Override
                            public void onError(Platform platform, int i, Throwable throwable) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(activity, "分享失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                            @Override
                            public void onCancel(Platform platform, int i) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(activity, "取消分享", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        });

                        // 启动分享GUI
                        oks.show(activity);

                    }
                });
            }
        }).start();
    }



    public static boolean checkURL(Activity activity, String url) {
        CustomTrust customTrust = new CustomTrust(activity);

        try {
            OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
            httpClientBuilder
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS);

            if (!TextUtils.isEmpty(url) && url.startsWith("https")) {
                // 添加https
                httpClientBuilder
                        .sslSocketFactory(customTrust.sslSocketFactory, customTrust.trustManager)
                        .hostnameVerifier(new UnSafeHostnameVerifier());
            }

            OkHttpClient httpClient = httpClientBuilder.build();
            Request request = new Request.Builder().url(url).build();
            Response response = httpClient.newCall(request).execute();

            return response.isSuccessful();

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 分享Url到微信朋友圈
     *
     * @param title    标题
     * @param shareUrl web地址
     * @param iconUrl  分享icon
     */
    public static void shareUrlToWeChatMoment(final Activity activity, final String title,
                                              final String shareUrl, final String iconUrl) {

        byte[] icon;
        if (TextUtils.isEmpty(iconUrl)) {
            icon = Utils.Image.bitmap2Bytes(BitmapFactory.decodeResource(activity.getResources(), R.mipmap.ic_launcher), false);
            shareUrlToWeChatMoment(WXAPIFactory.createWXAPI(activity, BuildConfig.WECHAT_APP_ID),
                    title,
                    shareUrl,
                    icon,
                    String.valueOf(System.currentTimeMillis()));
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        final byte[] icon = Utils.Image.getImageBytesFromUrl(iconUrl);
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                shareUrlToWeChatMoment(WXAPIFactory.createWXAPI(activity, BuildConfig.WECHAT_APP_ID),
                                        title,
                                        shareUrl,
                                        icon,
                                        String.valueOf(System.currentTimeMillis()));
                            }
                        });
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    /**
     * 分享Url到微信朋友圈
     *
     * @param api         微信api
     * @param title       标题
     * @param shareUrl    web地址
     * @param icon        分享icon
     * @param transaction
     */
    private static void shareUrlToWeChatMoment(IWXAPI api, String title, String shareUrl,
                                               byte[] icon, String transaction) {
        WXWebpageObject localWXWebpageObject = new WXWebpageObject();
        localWXWebpageObject.webpageUrl = shareUrl;
        WXMediaMessage localWXMediaMessage = new WXMediaMessage(
                localWXWebpageObject);
        localWXMediaMessage.title = title;
        localWXMediaMessage.description = title;
        localWXMediaMessage.thumbData = icon;
        SendMessageToWX.Req localReq = new SendMessageToWX.Req();
        localReq.transaction = transaction;
        localReq.message = localWXMediaMessage;
        localReq.scene = SendMessageToWX.Req.WXSceneTimeline;
        api.sendReq(localReq);
    }
}
